//
//  LJRecomentViewController.m
//  百思不得姐
//
//  Created by 刘鹿杰 on 16/7/13.
//  Copyright © 2016年 刘鹿杰. All rights reserved.
//

#import "LJRecomentViewController.h"
#import <AFNetworking.h>
#import <SVProgressHUD.h>
#import "LJLeftTableViewCell.h"
#import "LJRightTableViewCell.h"
#import <MJRefresh.h>
#import <MJExtension.h>
#import "LJleftModel.h"
#import "LJUserModel.h"


#define LJSelectedModel self.leftArray[self.leftTableView.indexPathForSelectedRow.row]

static  NSString * const LJLeftCellIdentifier = @"LeftCellIdentifier";
static  NSString * const LJRigthCellIdentifier = @"RigthCellIdentifier1";


@interface LJRecomentViewController ()<UITableViewDelegate, UITableViewDataSource>

/** 左侧列表tableView */
@property (weak, nonatomic) IBOutlet UITableView *leftTableView;
@property (weak, nonatomic) IBOutlet UITableView *rightTableView;

/** 存储刷新时字典变化 */
@property (nonatomic, strong) NSMutableDictionary *params;

/** AFN请求管理者 */
@property (nonatomic, strong) AFHTTPSessionManager *manager;

/** leftTableViewArray */
@property (nonatomic, strong) NSMutableArray *leftArray;

@end

@implementation LJRecomentViewController

-(AFHTTPSessionManager *)manager{
    if (!_manager) {
        _manager = [[AFHTTPSessionManager alloc] init];
        
    }
    return _manager;
}

-(void)viewDidLoad{
    
    [super viewDidLoad];
    
    // 注册Cell
    [self setUpTableView];
    
    // 添加刷新控件
    [self setUpRefrash];
    
    //加在左侧的数据
    [self loadLeftDate];
    
}

//  控件的初始化
-(void)setUpTableView{
    
    [self.leftTableView registerNib:[UINib nibWithNibName:NSStringFromClass([LJLeftTableViewCell class]) bundle:nil] forCellReuseIdentifier:LJLeftCellIdentifier];
    
    [self.rightTableView registerNib:[UINib nibWithNibName:NSStringFromClass([LJRightTableViewCell class]) bundle:nil] forCellReuseIdentifier:LJRigthCellIdentifier];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.leftTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    self.rightTableView.contentInset = self.leftTableView.contentInset;
    self.title = @"推荐关注";
    self.rightTableView.rowHeight = 70;
    self.view.backgroundColor = LJGlobalBg;
    
}

// 添加刷新控件
-(void)setUpRefrash{
    
    self.rightTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(LoadNewDete)];
    
    self.rightTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreUsers)];

     self.rightTableView.mj_footer.hidden = YES;
}


// 加载左侧数据
-(void)loadLeftDate{
    // 显示指示器
    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeBlack];
    
    // 发送请求
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"category";
    params[@"c"] = @"subscribe";
    
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [SVProgressHUD dismiss];
        
        self.leftArray =[LJleftModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        [self.leftTableView reloadData];
        
        // 选中左侧tableView第一条数据
        [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
        
        // 上来先刷新第一条数据
        [self.rightTableView.mj_header beginRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [SVProgressHUD showErrorWithStatus:@"加载推荐信息失败!"];
        
    }];
}



#pragma mark - <UITableViewDataSource>

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    // 检查控件底部状态
    [self checkFooterState];
    
    if (tableView == self.rightTableView) {
            return [LJSelectedModel userArray].count;
        
    }else return self.leftArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (tableView == self.rightTableView) {
        LJRightTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:LJRigthCellIdentifier];
        cell.userModel = [LJSelectedModel userArray][indexPath.row];
        return cell;

    }else{
        LJLeftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LJLeftCellIdentifier];
        cell.leftModel = self.leftArray[indexPath.row];
        return cell;
    }
 
}

#pragma mark - <UITableViewDelegate>
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.rightTableView.mj_header endRefreshing];
    
    LJleftModel * leftModel = LJSelectedModel;
    
    if (leftModel.userArray.count) {
        
     [self.rightTableView reloadData];
        
    }else{
     
     [self.rightTableView reloadData];
        
     [self.rightTableView.mj_header beginRefreshing];
   
    }
    
}

#pragma mark - 加载用户数据
-(void)LoadNewDete{
        LJLOGFUN;
        LJleftModel * leftModel = LJSelectedModel;
        leftModel.currentPage = 1;
    
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"a"] = @"list";
        params[@"c"] = @"subscribe";
        params[@"category_id"] = @(leftModel.id);
        params[@"page"] = @(leftModel.currentPage);
        self.params = params;
    

        [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSMutableArray *array =  [LJUserModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];

            // 移除所有的子元素
            [leftModel.userArray removeAllObjects];
            
            //添加加载出来的新的元素
            [leftModel.userArray addObjectsFromArray:array];
            
            // 给这个子模块有多少元素赋值
            leftModel.total = [responseObject[@"total"] integerValue];
            
            if (self.params != params) return ;
            
            // 刷新右侧的tableView
            [self.rightTableView reloadData];
            
            // 结束刷新的状态
            [self.rightTableView.mj_header endRefreshing];
            
            // 检查控件底部状态
            [self checkFooterState];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            // 此次刷新已经不再重要
            if (self.params != params) return;
            // 提醒
            [SVProgressHUD showErrorWithStatus:@"加载用户数据失败"];
            
            // 结束刷新
            [self.rightTableView.mj_header endRefreshing];

        }];
}

-(void)loadMoreUsers{
    
    LJLOGFUN;
    LJleftModel * leftModel = LJSelectedModel;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"subscribe";
    params[@"category_id"] = @(leftModel.id);
    params[@"page"] = @(++leftModel.currentPage);
    self.params = params;
    
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSMutableArray *array =  [LJUserModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        [leftModel.userArray addObjectsFromArray:array];
        
        if (self.params != params) return;
        
        [self.rightTableView reloadData];
        
        // 检查控件底部状态
        [self checkFooterState];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if ( self.params != params)return ;
        [SVProgressHUD showErrorWithStatus:@"加载用户数据失败"];
        
        [self.rightTableView.mj_footer endRefreshing];
    }];
    
}

// 监测网络状态
- (void)checkFooterState{
    
    LJleftModel * leftModel = LJSelectedModel;
    
    self.rightTableView.mj_footer.hidden = ([leftModel userArray].count == 0);
    
    if (leftModel.userArray.count == leftModel.total) {
        [self.rightTableView.mj_footer endRefreshingWithNoMoreData];
    }else{
        [self.rightTableView.mj_footer endRefreshing];
    }
}

-(void)dealloc{
    
    // 这个是非常有必要的, 当控制器不在的时候, 取消队列中的所有请求
    [self.manager.operationQueue cancelAllOperations];
}


@end
